﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.IO;
using System.Text.RegularExpressions;
namespace Utilities
{
    public class Rule
    {
        public String patternI, patternO, pattern;

        public Rule(String pI, String pO, String p)
        {
            patternI = pI;
            patternO = pO;
            pattern = p;
        }

        String MatchO(Match m)
        {
            String res = m.ToString();
            res = Regex.Replace(res, pattern, patternO);
            return res;
        }

        public String ReplacePatternS(String st)
        {
            return Regex.Replace(st, patternI, new MatchEvaluator(MatchO));
        }
        public String ReplacePattern(String st)
        {
            String res = "";
            MatchCollection matches = Regex.Matches(st, patternI);
            int start = 0;
            if (matches.Count > 0)
            {
                foreach (Match match in matches)
                {
                    String key = match.Value;
                    String pattern = ReplacePatternS(key);

                    res = res + st.Substring(start, match.Index - start);
                    res = res + pattern;
                    start = match.Index + match.Length;
                }
            }
            res = res + st.Substring(start, st.Length - start);

            return res;
        }
    }
}